package com.tianyi.productInfo;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.tianyi.dao.entity.brand.Brand;
import com.tianyi.dao.entity.productInfo.ProductInfo;
import com.tianyi.dao.entity.productInfo.ProductInfoExample;
import com.tianyi.dao.entity.productPhoto.ProductPhoto;
import com.tianyi.dao.entity.productPhoto.ProductPhotoExample;
import com.tianyi.dao.mapper.BrandMapper;
import com.tianyi.dao.mapper.CommMapper;
import com.tianyi.dao.mapper.ProductInfoMapper;
import com.tianyi.dao.mapper.ProductPhotoMapper;
import com.tianyi.fileUpload.FileUploadService;
import com.tianyi.lib.req.ProductReq;
import com.tianyi.lib.result.ColorPriceInventory;
import com.tianyi.lib.result.ProductInfoOrderResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品base service
 *
 * @author cuixuhui
 * @date 2020/06/20
 */
@Service
public class ProductBaseService {

    private static final Logger logger = LoggerFactory.getLogger(ProductBaseService.class);

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Autowired
    private ProductPhotoMapper productPhotoMapper;

    @Autowired
    private CommMapper commMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private FileUploadService fileUploadService;

    //======================================product==================================================

    public ProductInfo queryProductInfoById(Long id) {
        return productInfoMapper.selectByPrimaryKey(id);
    }

    public List<ProductInfo> queryProductInfoByProductNoName(String productNo, String productName) {

        ProductInfoExample example = new ProductInfoExample();
        example.createCriteria().andProductNameEqualTo(productName).andProductNoEqualTo(productNo);
        return productInfoMapper.selectByExample(example);
    }

    public ProductInfo gentInsertProductByReq(ProductReq req) {

        ProductInfo info = new ProductInfo();
        BeanUtils.copyProperties(req, info);

        info.setGmtCreate(new Date());
        info.setGmtModified(new Date());
        info.setOperator(req.getEmpId());
        info.setStatus(req.getStatus().toString());
        info.setVersion(1);
        return info;
    }

    public ProductInfo insertProductInfo(ProductInfo productInfo) {

        if (Objects.isNull(productInfo)){
            return null;
        }
        int insert = productInfoMapper.insert(productInfo);
        return productInfo;
    }

    public Integer deleteProductInfoById(Long productId) {

        return productInfoMapper.deleteByPrimaryKey(productId);
    }

    public PageInfo<ProductInfoOrderResult> queryProductInfoPage(ProductReq req){

        ProductInfoExample example = new ProductInfoExample();
        Page<ProductInfo> productInfos = productInfoMapper.selectByExample(example, new RowBounds(req.getPageNo(), req.getPageSize()));
        PageInfo<ProductInfo> pageInfos = productInfos.toPageInfo();
        PageInfo<ProductInfoOrderResult> productPageInfos = new PageInfo<>();
        BeanUtils.copyProperties(pageInfos, productPageInfos);
        List<ProductInfo> pageInfosList = pageInfos.getList();
        HashMap<String,HashMap<String,ColorPriceInventory>> productNumberMap = new HashMap<>();
        HashMap<String,ProductInfo> productInfoHashMap = new HashMap<>();
        //HashMap<String,ProductInfo> productNumberMap = new HashMap();

        for(ProductInfo info : pageInfosList){
            if(productNumberMap.containsKey(info.getProductNo())){
                if(productNumberMap.get(info.getProductNo()).containsKey(info.getColour())){
                    long count = productNumberMap.get(info.getProductNo()).get(info.getColour()).getInventory();
                    ColorPriceInventory colorPriceInventory = new ColorPriceInventory();
                    colorPriceInventory.setColor(info.getColour());
                    colorPriceInventory.setPrice(info.getPrice().doubleValue());
                    colorPriceInventory.setInventory(count+info.getInventory());
                    productNumberMap.get(info.getProductNo()).put(info.getColour()+"", colorPriceInventory);
                }else{
                    productNumberMap.get(info.getProductNo()).put(info.getColour()+"", makeColorPriceInventory(info));
                }
            }else{
                HashMap<String,ColorPriceInventory> colorPriceInventoryHashMap = new HashMap<>();
                //colorPriceInventoryHashMap.put(info.getColour()+"", makeColorPriceInventory(info));
                //productNumberMap.put(info.getProductNo()+"",colorPriceInventoryHashMap);
            }

            if(productInfoHashMap.containsKey(info.getProductNo())){

            }else{
                productInfoHashMap.put(info.getProductNo()+"", info);
            }
        }

        List<ProductInfoOrderResult> resultsList = new ArrayList<>();
        for(Map.Entry<String,HashMap<String,ColorPriceInventory>> entry : productNumberMap.entrySet()){
            List<ColorPriceInventory> colorPriceInventories = new ArrayList<>();
            long countTemp = 0L;
            for(Map.Entry<String,ColorPriceInventory> colorPriceInventoryEntry : entry.getValue().entrySet()){
                colorPriceInventories.add(colorPriceInventoryEntry.getValue());
                countTemp += colorPriceInventoryEntry.getValue().getInventory();
            }
            ProductInfoOrderResult productInfoOrderResult = new ProductInfoOrderResult();
            ProductInfo info = productInfoHashMap.get(entry.getKey());
            productInfoOrderResult.setAnnual(info.getAnnual());
            productInfoOrderResult.setQuarter(info.getQuarter());
            productInfoOrderResult.setBrandId(info.getBrandId());
            productInfoOrderResult.setClassifyId(info.getClassifyId());
            productInfoOrderResult.setOpenEnd(info.getOpenEnd());
            productInfoOrderResult.setOpenStart(info.getOpenStart());
            if(info.getPrice()!=null) {
                productInfoOrderResult.setPrice(info.getPrice().doubleValue());
            }
            productInfoOrderResult.setProductName(info.getProductName());
            productInfoOrderResult.setProductNo(info.getProductNo());
            productInfoOrderResult.setCargoList(colorPriceInventories);
            productInfoOrderResult.setOperator(info.getOperator());
            productInfoOrderResult.setInventory(countTemp);
            productInfoOrderResult.setExt1(info.getExt1());
            Brand brand = new Brand();
            try{
                brand = brandMapper.selectByPrimaryKey(info.getBrandId());
            }catch (Exception e){

            }
            if(brand != null) {
                productInfoOrderResult.setBrandName(brand.getBrandName());
            }
            resultsList.add(productInfoOrderResult);
        }
        productPageInfos.setList(resultsList);
        return productPageInfos;
    }

    private ColorPriceInventory makeColorPriceInventory(ProductInfo info){
        ColorPriceInventory colorPriceInventory = new ColorPriceInventory();
        colorPriceInventory.setPrice(info.getPrice().doubleValue());
        colorPriceInventory.setInventory(info.getInventory());
        colorPriceInventory.setColor(info.getColour());
        return colorPriceInventory;
    }

    //======================================photo==================================================

    /**
     * 保存文件
     * @param productInfoId
     * @param req
     * @return
     */
    public ProductPhoto gentBaseProductPhotoByReq(Long productInfoId, ProductReq req) {

        ProductPhoto productPhoto = new ProductPhoto();

        productPhoto.setGmtCreate(new Date());
        productPhoto.setGmtModified(new Date());

        productPhoto.setPhotoPath(req.getPhotoPath());
        productPhoto.setProductId(productInfoId);
        return productPhoto;
    }

    public ProductPhoto insertProductPhoto(ProductPhoto productPhoto) {

        if (Objects.isNull(productPhoto)){
            return null;
        }
        int insert = productPhotoMapper.insert(productPhoto);
        return productPhoto;
    }

    public List<ProductPhoto>  queryProductPhotoByProductIds(List<Long> productIds) {

        ProductPhotoExample example = new ProductPhotoExample();
        ProductPhotoExample.Criteria criteria = example.createCriteria();
        criteria.andProductIdIn(productIds);

        List<ProductPhoto> productPhotos = productPhotoMapper.selectByExample(example);
        return productPhotos;
    }


    public void deleteProductPhotoByProductId(Long productId) {

        List<String> photoPaths = deleteProductPhotoByProductIdWithoutDeleteFile(productId);

        if (CollectionUtils.isEmpty(photoPaths)){
            return;
        }
        //todo 建议做成异步
        for (String photoPath : photoPaths) {
            fileUploadService.deletePhotoWithThumbnails(photoPath);
        }
    }

    /**
     * 删除记录without path
     * @param productId
     * @return
     */
    public List<String>  deleteProductPhotoByProductIdWithoutDeleteFile(Long productId) {

        List<ProductPhoto> productPhotos = queryProductPhotoByProductIds(Arrays.asList(productId));
        if (CollectionUtils.isEmpty(productPhotos)){
            return new ArrayList<>();
        }

        List<Long> ids = productPhotos.stream().map(ProductPhoto::getId).collect(Collectors.toList());
        int deleteByIds = productPhotoMapper.batchDeleteByIds(ids);

        //todo 建议做成异步
        List<String> photoPaths = productPhotos.stream().map(ProductPhoto::getPhotoPath).collect(Collectors.toList());
        return photoPaths;
    }

    public void updateProductPhoto(ProductPhoto productPhoto) {
        if (Objects.isNull(productPhoto)){
            return;
        }
        productPhotoMapper.updateByPrimaryKey(productPhoto);
    }

    /**
     * 修改产品信息by乐观锁
     *
     * @param productInfo
     */
    public Integer updateProductInfoWithVersion(ProductInfo productInfo) {

        if (Objects.isNull(productInfo)){
            return 0;
        }
        //return commMapper.updateProductInfoByVersion(productInfo);
        return productInfoMapper.updateByPrimaryKey(productInfo);
    }
}
